package sqlitedb

import (
	"database/sql"
	"fmt"
	"reflect"

	us "gitee.com/gouyabin/go_utils"
	_ "github.com/mattn/go-sqlite3"
)

const (
	SqlField = "sqlField" //自创建数据库字段名称标记
	SqlType  = "sqlType"  //自创建数据库字段类型标记
)

var DBUrl string //数据库连接

var CONN *sql.DB //数据库状态

var Log *us.Logs

func InitDBMode() {
	Log = us.Log
	isPath, err := us.PathExists(DBUrl, false) //判断数据库文件是否存在
	Log.Info("数据库地址：", DBUrl)
	CONN, err = sql.Open("sqlite3", DBUrl)
	if !isPath {
		fmt.Println("数据库文件不存在..")
		CreateAllTablese() //不存在，创建数据库表格式
	} else {
		fmt.Println("数据库文件存在..")
	}
	us.CheckErr(err)
	fmt.Println("打开数据库")
}

func CreateAllTablese() {
	createUserDB()
	createGroupTypeDB()
	createUserGroupTypeDB()

}

//根据结构类型，以及结构后面的tag 创建数据库结构
func createTablesStruct(td interface{}, tablename string) {
	t := reflect.TypeOf(td)
	createTableCmd := "CREATE TABLE IF NOT EXISTS "
	tableFieldStr := ""
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		typeTag := field.Tag.Get(SqlType)
		tableTag := field.Tag.Get(SqlField)
		if typeTag == "" || tableTag == "" {
			continue
		}
		if i != 0 {
			tableFieldStr = tableFieldStr + ","
		}
		tableFieldStr = tableFieldStr + tableTag + " " + typeTag
		// fmt.Printf("%d. %v(%v), tag:'%v'\n", i+1, field.Name, field.Type.Name(), typeTag)
	}
	createTableCmd = createTableCmd + tablename + "(" + tableFieldStr + ")"
	fmt.Println("sqlCmd:", createTableCmd)
	CONN.Exec(createTableCmd)
}
